import { generateDeclarationFile } from './utils.js';
import { Extractor, ExtractorConfig } from '@microsoft/api-extractor';
import { resolve } from 'node:path';
import { mkdir } from 'node:fs/promises';

export default async function buildPluginSdk() {
  // Ensure the output directory exists
  const outDir = resolve(process.cwd(), 'tmp/plugin-sdk/unbundled-types');
  await mkdir(outDir, { recursive: true });

  try {
    generateDeclarationFile(
      {
        [resolve(process.cwd(), 'src/plugin-sdk/index.tsx')]: 'index',
      },
      outDir,
    );
  } catch (error) {
    console.error('Failed to generate declaration file:', error);
    throw error;
  }

  const extractorConfig = ExtractorConfig.loadFileAndPrepare(
    resolve(process.cwd(), 'api-extractor-configs/plugin-sdk.json'),
  );

  Extractor.invoke(extractorConfig, {});
}
